package me.zhengjie.modules.vip.service.impl;

import cn.hutool.core.bean.BeanUtil;
import me.zhengjie.modules.vip.domain.MemberLevels;
import me.zhengjie.modules.vip.domain.Members;
import me.zhengjie.modules.vip.domain.dto.MemberLevelsDto;
import me.zhengjie.modules.vip.service.MemberLevelsService;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.vip.service.MembersService;
import me.zhengjie.modules.vip.domain.vo.MembersQueryCriteria;
import me.zhengjie.modules.vip.mapper.MembersMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import me.zhengjie.utils.PageResult;
import me.zhengjie.exception.BadRequestException;
import org.apache.commons.lang3.StringUtils;

import java.util.logging.Logger;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.vip.domain.MemberCards;
import me.zhengjie.modules.vip.service.MemberCardsService;

/**
* @description 服务实现
* @author ck
* @date 2024-12-20
**/
@Service
@RequiredArgsConstructor
public class MembersServiceImpl extends ServiceImpl<MembersMapper, Members> implements MembersService {

    private final MembersMapper membersMapper;
    private final MemberCardsService memberCardsService;
    @Autowired
    private DictDetailService dictDetailService;
    private final MemberLevelsService memberLevelsService;

    // 手机号正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    @Override
    public PageResult<Members> queryAll(MembersQueryCriteria criteria, Page<Object> page){
        List<Members> members = PageUtil.toPage(membersMapper.findAll(criteria, page)).getContent();
        List<Members> updatedMembers = members.stream()
            .map(this::getByMember)
            .collect(Collectors.toList());
        return PageUtil.toPage(updatedMembers);
    }

    @Override
    public List<Members> queryAll(MembersQueryCriteria criteria){
        List<Members> membersList = membersMapper.findAll(criteria);
        membersList.forEach(this::getByMember);
        return membersList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Members resources) {
        validateMember(resources);
        // 检查手机号是否已存在
        Long count = lambdaQuery()
            .eq(Members::getPhone, resources.getPhone())
            .count();
        if (count > 0) {
            throw new BadRequestException("该手机号已被注册");
        }
        
        // 保存会员基本信息
        save(resources);
        
        // 如果有会员卡信息，保存会员卡
        if (resources.getCardIds() != null && !resources.getCardIds().isEmpty()) {
            for (String cardNumber : resources.getCardIds()) {
                MemberCards card = new MemberCards();
                card.setMemberId(resources.getId());
                card.setCardNo(cardNumber);
                memberCardsService.save(card);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Members resources) {
        validateMember(resources);
        Members members = getByMember(resources);
        if (members == null) {
            throw new BadRequestException("会员不存在");
        }
        // 如果修改了手机号，需要检查新手机号是否已被使用
        if (!members.getPhone().equals(resources.getPhone())) {
            Long count = lambdaQuery()
                .eq(Members::getPhone, resources.getPhone())
                .ne(Members::getId, resources.getId())
                .count();
            if (count > 0) {
                throw new BadRequestException("该手机号已被其他会员使用");
            }
        }
        members.copy(resources);
        saveOrUpdate(members);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Members> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Members members : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("会员姓名", members.getName());
            map.put("手机号", members.getPhone());
            map.put("会员卡号列表", members.getCardIds());
            map.put("会员等级ID", members.getLevelId());
            map.put("当前积分", members.getCurrentPoints());
            map.put("备注", members.getRemarks());
            map.put("创建时间", members.getCreatedAt());
            map.put("更新时间", members.getUpdatedAt());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    public Members getByMember(Members members) {
        Long id = members.getId();
        Members member = super.getById(id);
        if (member != null) {
            // 查询关联的会员卡信息
            List<MemberCards> cards = memberCardsService.lambdaQuery()
                .eq(MemberCards::getMemberId, id)
                .list();
            
            // 转换每个卡的 cardType 从 value 到 label
            cards.forEach(card -> {
                List<DictDetail> dictDetails = dictDetailService.getDictDetailsByDictValue(card.getCardType());
                if (!dictDetails.isEmpty()) {
                    card.setCardType(dictDetails.get(0).getLabel());
                }
            });

            // 查询会员等级信息
            MemberLevelsDto memberLevelsDto = memberLevelsService.findById(member.getLevelId());
            if (memberLevelsDto != null) {
                member.setMemberLevels(BeanUtil.copyProperties(memberLevelsDto, MemberLevels.class));
            }

            member.setMemberCards(cards);
            member.setCardIds(cards.stream()
                .map(MemberCards::getCardNo)
                .collect(Collectors.toList()));
        }
        return member;
    }

    /**
     * 验证会员信息
     * @param members 会员信息
     */
    private void validateMember(Members members) {
        if (StringUtils.isBlank(members.getName())) {
            throw new BadRequestException("会员姓名不能为空");
        }
        if (StringUtils.isBlank(members.getPhone())) {
            throw new BadRequestException("手机号不能为空");
        }
        if (!Pattern.matches(PHONE_REGEX, members.getPhone())) {
            throw new BadRequestException("手机号格式不正确");
        }
        if (members.getLevelId() == null) {
            members.setLevelId(1); // 设置默认等级为1
        }
        if (members.getCurrentPoints() == null) {
            members.setCurrentPoints(0); // 设置默认积分为0
        }
    }
}